<template>
  <div class="config-manage-container">
    <h1 class="page-title">配置管理</h1>
    
    <!-- 搜索和操作区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="配置分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>
            <el-option 
              v-for="item in categoryOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="配置名称">
          <el-input v-model="searchForm.name" placeholder="请输入配置名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      
      <div class="operation-buttons">
        <el-button type="primary" @click="handleAdd">新增配置</el-button>
        <el-button type="success" @click="handleImport">导入配置</el-button>
        <el-button type="warning" @click="handleExport">导出配置</el-button>
        <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">
          批量删除
        </el-button>
      </div>
    </el-card>
    
    <!-- 配置列表 -->
    <el-card class="table-card">
      <el-table 
        :data="tableData" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
        border
        style="width: 100%">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="category" label="分类" width="120">
          <template #default="scope">
            <el-tag :type="getCategoryTagType(scope.row.category)">
              {{ getCategoryLabel(scope.row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="配置名称" width="180"></el-table-column>
        <el-table-column prop="key" label="配置键" width="200"></el-table-column>
        <el-table-column prop="value" label="配置值" show-overflow-tooltip></el-table-column>
        <el-table-column prop="description" label="描述" show-overflow-tooltip></el-table-column>
        <el-table-column prop="updatedAt" label="更新时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.updatedAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 新增/编辑配置对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="600px"
      @close="handleDialogClose">
      <el-form :model="configForm" :rules="configRules" ref="configFormRef" label-width="100px">
        <el-form-item label="配置分类" prop="category">
          <el-select v-model="configForm.category" placeholder="请选择分类" style="width: 100%">
            <el-option 
              v-for="item in categoryOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="配置名称" prop="name">
          <el-input v-model="configForm.name" placeholder="请输入配置名称"></el-input>
        </el-form-item>
        <el-form-item label="配置键" prop="key">
          <el-input v-model="configForm.key" placeholder="请输入配置键"></el-input>
        </el-form-item>
        <el-form-item label="配置值" prop="value">
          <el-input 
            v-model="configForm.value" 
            type="textarea" 
            :rows="3"
            placeholder="请输入配置值"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="configForm.description" 
            type="textarea" 
            :rows="2"
            placeholder="请输入描述"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 导入配置对话框 -->
    <el-dialog v-model="importDialogVisible" title="导入配置" width="500px">
      <el-upload
        ref="uploadRef"
        :auto-upload="false"
        :limit="1"
        accept=".json,.xlsx,.xls"
        :on-change="handleFileChange"
        :file-list="fileList">
        <el-button type="primary">选择文件</el-button>
        <template #tip>
          <div class="el-upload__tip">
            支持JSON、Excel格式文件，文件大小不超过10MB
          </div>
        </template>
      </el-upload>
      <template #footer>
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleImportSubmit" :loading="importLoading">导入</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getConfigList,
  createConfig,
  updateConfig,
  deleteConfig,
  batchDeleteConfig,
  getConfigCategories,
  exportConfig,
  importConfig
} from '@/api/config'

// 搜索表单
const searchForm = reactive({
  category: '',
  name: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const configFormRef = ref(null)
const configForm = reactive({
  id: null,
  category: '',
  name: '',
  key: '',
  value: '',
  description: ''
})

// 表单验证规则
const configRules = {
  category: [{ required: true, message: '请选择配置分类', trigger: 'change' }],
  name: [{ required: true, message: '请输入配置名称', trigger: 'blur' }],
  key: [{ required: true, message: '请输入配置键', trigger: 'blur' }],
  value: [{ required: true, message: '请输入配置值', trigger: 'blur' }]
}

// 分类选项
const categoryOptions = ref([])

// 导入相关
const importDialogVisible = ref(false)
const uploadRef = ref(null)
const fileList = ref([])
const importLoading = ref(false)

// 获取分类标签
const getCategoryLabel = (value) => {
  const option = categoryOptions.value.find(item => item.value === value)
  return option ? option.label : value
}

// 获取分类标签类型
const getCategoryTagType = (value) => {
  const typeMap = {
    'system': 'danger',
    'api': 'primary',
    'ui': 'success',
    'security': 'warning',
    'notification': 'info'
  }
  return typeMap[value] || ''
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString()
}

// 获取配置列表
const fetchConfigList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      ...searchForm
    }
    const response = await getConfigList(params)
    tableData.value = response.data.list || []
    pagination.total = response.data.total || 0
  } catch (error) {
    console.error('获取配置列表失败:', error)
    ElMessage.error('获取配置列表失败')
  } finally {
    loading.value = false
  }
}

// 获取配置分类
const fetchConfigCategories = async () => {
  try {
    const response = await getConfigCategories()
    categoryOptions.value = response.data || []
  } catch (error) {
    console.error('获取配置分类失败:', error)
    // 使用默认分类
    categoryOptions.value = [
      { value: 'system', label: '系统配置' },
      { value: 'api', label: 'API配置' },
      { value: 'ui', label: '界面配置' },
      { value: 'security', label: '安全配置' },
      { value: 'notification', label: '通知配置' }
    ]
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchConfigList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    category: '',
    name: ''
  })
  pagination.currentPage = 1
  fetchConfigList()
}

// 新增配置
const handleAdd = () => {
  dialogTitle.value = '新增配置'
  dialogVisible.value = true
  Object.assign(configForm, {
    id: null,
    category: '',
    name: '',
    key: '',
    value: '',
    description: ''
  })
}

// 编辑配置
const handleEdit = (row) => {
  dialogTitle.value = '编辑配置'
  dialogVisible.value = true
  Object.assign(configForm, {
    id: row.id,
    category: row.category,
    name: row.name,
    key: row.key,
    value: row.value,
    description: row.description
  })
}

// 删除配置
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除配置"${row.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteConfig(row.id)
      ElMessage.success('删除成功')
      fetchConfigList()
    } catch (error) {
      console.error('删除配置失败:', error)
      ElMessage.error('删除配置失败')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 批量删除
const handleBatchDelete = () => {
  const ids = selectedRows.value.map(row => row.id)
  ElMessageBox.confirm(`确定要删除选中的${ids.length}个配置吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await batchDeleteConfig(ids)
      ElMessage.success('批量删除成功')
      fetchConfigList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  fetchConfigList()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchConfigList()
}

// 提交表单
const handleSubmit = async () => {
  try {
    await configFormRef.value.validate()
    
    if (configForm.id) {
      // 更新
      await updateConfig(configForm.id, configForm)
      ElMessage.success('更新成功')
    } else {
      // 新增
      await createConfig(configForm)
      ElMessage.success('新增成功')
    }
    
    dialogVisible.value = false
    fetchConfigList()
  } catch (error) {
    if (error.message) {
      console.error('提交失败:', error)
      ElMessage.error('提交失败')
    }
  }
}

// 对话框关闭
const handleDialogClose = () => {
  configFormRef.value?.resetFields()
}

// 导入配置
const handleImport = () => {
  importDialogVisible.value = true
  fileList.value = []
}

// 文件变化
const handleFileChange = (file, fileList) => {
  // 这里可以添加文件类型和大小验证
}

// 提交导入
const handleImportSubmit = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请选择要导入的文件')
    return
  }
  
  importLoading.value = true
  try {
    const formData = new FormData()
    formData.append('file', fileList.value[0].raw)
    
    await importConfig(formData)
    ElMessage.success('导入成功')
    importDialogVisible.value = false
    fetchConfigList()
  } catch (error) {
    console.error('导入失败:', error)
    ElMessage.error('导入失败')
  } finally {
    importLoading.value = false
  }
}

// 导出配置
const handleExport = async () => {
  try {
    const params = { ...searchForm }
    const response = await exportConfig(params)
    
    // 创建下载链接
    const blob = new Blob([response.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `config_${new Date().getTime()}.json`
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 初始化
onMounted(() => {
  fetchConfigCategories()
  fetchConfigList()
})
</script>

<style scoped>
.config-manage-container {
  padding: 20px;
}

.page-title {
  font-size: 24px;
  margin-bottom: 20px;
  color: #333;
}

.search-card {
  margin-bottom: 20px;
}

.operation-buttons {
  margin-top: 15px;
  display: flex;
  gap: 10px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>